# -*- coding:utf-8 -*-
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

import time
from . import tests
from . import task

from tool.socket.tcpserver import Tcpserver
from tool.socket.updserver import Udpserver


socketServer = Udpserver(10012)
taskThread = task.deviceTaskThread('deviceStatus')
MAX_TASK_LIST = 5

def run():
    updataDeviceStaus() # 请求所有设备状态
    # createDeviceStatusJson()
    taskThread.start()

def updataDeviceStaus():
    str_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    taskThread.pushTak(str_time, socketServer.initConnect, ('FFFF',3,3))
   
'''
_time: 指定任务开始 的时间
'''
def sendCmdToDevice(_time, _ip, _cmd):
    str_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    TaskThread.pushTak(_time ,socketServer.sendMessage, (_ip, _cmd))

def createDeviceStatusJson():
    devices = tests.getAllDevice()
    all_info = ''
    for device in devices:
        all_info += str(device) + '\n,'
    result = '{ \"deviceData\":[\n\t' + all_info.rstrip('\,') + ']}'
    path = 'js/data/datagrid.json'
    default_storage.delete(path)
    default_storage.save(path, ContentFile(result))

def createTask(_task_to_device, _wind_act, _water_act, _light_act, _device_status, _act_time):
    tests.createOneTask(_task_to_device, _wind_act, _water_act, _light_act, _device_status, _act_time)

def getTask():
    return tests.getAllTask()

def matchTask():
    return tests.getDeviceInfoById()
